import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_html/flutter_html.dart';
import '../../providers/technique_provider.dart';
import '../../models/fishing_technique.dart';
import '../../widgets/comment_section.dart';
import '../../widgets/image_preview.dart';
import '../../widgets/floating_action_bar.dart';
import '../../services/comment_service.dart';

class TechniqueDetailPage extends StatefulWidget {
  final String id;
  
  const TechniqueDetailPage({
    super.key,
    required this.id,
  });

  @override
  State<TechniqueDetailPage> createState() => _TechniqueDetailPageState();
}

class _TechniqueDetailPageState extends State<TechniqueDetailPage> {
  final CommentService _commentService = CommentService();
  final GlobalKey<CommentSectionState> _commentSectionKey = GlobalKey();
  bool _isFavorited = false;
  bool _isLiked = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = context.read<TechniqueProvider>();
      provider.loadTechniqueDetail(widget.id);
      provider.loadComments(widget.id, refresh: true);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  // 点赞功能
  void _toggleLike() async {
    try {
      final result = await _commentService.togglePostLike(
        postId: int.parse(widget.id),
        postType: 'technique',
      );
      
      if (result['success'] == true) {
        setState(() {
          _isLiked = !_isLiked;
        });
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(_isLiked ? '已点赞' : '已取消点赞'),
            duration: const Duration(seconds: 1),
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(result['message'] ?? '操作失败')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: ${e.toString()}')),
      );
    }
  }

  // 收藏功能
  void _toggleFavorite() async {
    try {
      final result = await _commentService.togglePostFavorite(
        postId: int.parse(widget.id),
        postType: 'technique',
      );
      
      if (result['success'] == true) {
        setState(() {
          _isFavorited = !_isFavorited;
        });
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(_isFavorited ? '已收藏' : '已取消收藏'),
            duration: const Duration(seconds: 1),
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(result['message'] ?? '操作失败')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: ${e.toString()}')),
      );
    }
  }

  // 显示提示信息
  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: true,
      bottomNavigationBar: _buildFloatingBottomBar(),
      body: Consumer<TechniqueProvider>(
        builder: (context, provider, child) {
          final technique = provider.currentTechnique;
          
          if (provider.isLoading || technique == null) {
            return const Scaffold(
              body: Center(child: CircularProgressIndicator()),
            );
          }

          return CustomScrollView(
            slivers: [
              _buildSliverAppBar(technique),
              SliverToBoxAdapter(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildHeader(technique),
                      const SizedBox(height: 24),
                      _buildContent(technique),
                      const SizedBox(height: 24),
                      _buildInteractionStats(technique),
                      const SizedBox(height: 24),
                      _buildTags(technique),
                      const SizedBox(height: 24),
                      _buildAuthorInfo(technique),
                      const SizedBox(height: 24),
                      // 评论组件
                      CommentSection(
                        key: _commentSectionKey,
                        postId: int.parse(widget.id),
                        postType: 'technique',
                        onCommentCountChanged: (count) {
                          // 可以在这里更新评论数量
                        },
                      ),
                      const SizedBox(height: 80), // 为悬浮底部栏留出空间
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  // 构建悬浮底部操作栏
  Widget _buildFloatingBottomBar() {
    return Consumer<TechniqueProvider>(
      builder: (context, provider, child) {
        final technique = provider.currentTechnique;
        if (technique == null) return const SizedBox.shrink();
        
        return FloatingActionBar(
          isLiked: _isLiked,
          likeCount: technique.likeCount,
          isFavorited: _isFavorited,
          commentCount: technique.commentCount,
          onLike: _toggleLike,
          onFavorite: _toggleFavorite,
          onComment: () {
            _commentSectionKey.currentState?.showCommentInputBottomSheet();
          },
        );
      },
    );
  }

  Widget _buildSliverAppBar(FishingTechnique technique) {
    return SliverAppBar(
      expandedHeight: 250,
      pinned: true,
      backgroundColor: Colors.blue[600],
      foregroundColor: Colors.white,
      flexibleSpace: FlexibleSpaceBar(
        background: Stack(
          fit: StackFit.expand,
          children: [
            technique.imageUrl.isNotEmpty
                ? Image.network(
                    technique.imageUrl,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return _buildDefaultBackground(technique.category);
                    },
                  )
                : _buildDefaultBackground(technique.category),
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.transparent,
                    Colors.black.withOpacity(0.7),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      actions: [
        // 点赞按钮（爱心）
        Consumer<TechniqueProvider>(
          builder: (context, provider, child) {
            final technique = provider.currentTechnique;
            final isLiked = technique?.isLiked ?? false;
            
            return IconButton(
              icon: Icon(
                isLiked ? Icons.favorite : Icons.favorite_border,
                color: isLiked ? Colors.red : Colors.white,
              ),
              onPressed: () {
                provider.toggleLike(widget.id);
              },
            );
          },
        ),
        // 收藏按钮（五角星）
        Consumer<TechniqueProvider>(
          builder: (context, provider, child) {
            final technique = provider.currentTechnique;
            final isFavorited = technique?.isFavorited ?? false;
            
            return IconButton(
              icon: Icon(
                isFavorited ? Icons.star : Icons.star_border,
                color: isFavorited ? Colors.amber : Colors.white,
              ),
              onPressed: () {
                provider.toggleFavorite(widget.id);
              },
            );
          },
        ),
        IconButton(
          icon: const Icon(Icons.share),
          onPressed: () {
            _showSnackBar('分享功能开发中...');
          },
        ),
      ],
    );
  }

  Widget _buildDefaultBackground(String category) {
    IconData icon;
    List<Color> colors;
    
    switch (category) {
      case '基础入门':
        icon = Icons.school;
        colors = [Colors.green[400]!, Colors.green[600]!];
        break;
      case '钓法技巧':
        icon = Icons.psychology;
        colors = [Colors.blue[400]!, Colors.blue[600]!];
        break;
      case '饵料配方':
        icon = Icons.science;
        colors = [Colors.orange[400]!, Colors.orange[600]!];
        break;
      case '装备选择':
        icon = Icons.build;
        colors = [Colors.purple[400]!, Colors.purple[600]!];
        break;
      case '钓点选择':
        icon = Icons.place;
        colors = [Colors.teal[400]!, Colors.teal[600]!];
        break;
      default:
        icon = Icons.waves;
        colors = [Colors.blue[400]!, Colors.blue[600]!];
    }

    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: colors,
        ),
      ),
      child: Center(
        child: Icon(
          icon,
          color: Colors.white.withOpacity(0.3),
          size: 80,
        ),
      ),
    );
  }

  Widget _buildHeader(FishingTechnique technique) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Text(
                technique.title,
                style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
            ),
            const SizedBox(width: 8),
            _buildDifficultyChip(technique.difficulty),
          ],
        ),
        
        if (technique.subtitle.isNotEmpty) ...[
          const SizedBox(height: 8),
          Text(
            technique.subtitle,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
        ],
        
        const SizedBox(height: 16),
        
        Row(
          children: [
            _buildStatItem(Icons.visibility, '${technique.readCount}', '阅读'),
            const SizedBox(width: 24),
            _buildStatItem(Icons.access_time, '${technique.estimatedReadTime}分钟', '阅读时间'),
          ],
        ),
      ],
    );
  }

  Widget _buildStatItem(IconData icon, String value, String label) {
    return Row(
      children: [
        Icon(icon, size: 16, color: Colors.grey[600]),
        const SizedBox(width: 4),
        Text(
          value,
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey[600],
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(width: 2),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[500],
          ),
        ),
      ],
    );
  }

  Widget _buildDifficultyChip(String difficulty) {
    Color color;
    switch (difficulty) {
      case '初级':
        color = Colors.green;
        break;
      case '中级':
        color = Colors.orange;
        break;
      case '高级':
        color = Colors.red;
        break;
      default:
        color = Colors.grey;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Text(
        difficulty,
        style: TextStyle(
          fontSize: 14,
          color: color,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }

  Widget _buildContent(FishingTechnique technique) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '内容详情',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 12),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.grey[50],
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.grey[200]!),
          ),
          child: _buildHtmlContent(technique.content),
        ),
      ],
    );
  }
  
  Widget _buildHtmlContent(String rawContent) {
    // 使用_decodeHtmlEntities处理HTML实体和图片URL
    String processedContent = _decodeHtmlEntities(rawContent);
    
    // 打印处理后的内容，用于调试
    
    // 如果内容包含HTML标签，使用Html widget渲染
    if (processedContent.contains('<') && processedContent.contains('>')) {
      return Html(
        data: processedContent,
        style: {
          "body": Style(
            margin: Margins.zero,
            padding: HtmlPaddings.zero,
            fontSize: FontSize(16),
            lineHeight: const LineHeight(1.6),
            color: Colors.black87,
          ),
          "h1": Style(
            fontSize: FontSize(24),
            fontWeight: FontWeight.bold,
            margin: Margins.only(bottom: 16),
            color: Colors.black87,
          ),
          "h2": Style(
            fontSize: FontSize(20),
            fontWeight: FontWeight.bold,
            margin: Margins.only(top: 16, bottom: 12),
            color: Colors.black87,
          ),
          "h3": Style(
            fontSize: FontSize(18),
            fontWeight: FontWeight.w600,
            margin: Margins.only(top: 12, bottom: 8),
            color: Colors.black87,
          ),
          "p": Style(
            margin: Margins.only(bottom: 12),
            fontSize: FontSize(16),
            lineHeight: const LineHeight(1.6),
          ),
          "a": Style(
            color: Colors.blue[600],
            textDecoration: TextDecoration.underline,
          ),
          "strong": Style(
            fontWeight: FontWeight.bold,
          ),
          "em": Style(
            fontStyle: FontStyle.italic,
          ),
          "ul": Style(
            margin: Margins.only(bottom: 12),
            padding: HtmlPaddings.only(left: 20),
          ),
          "ol": Style(
            margin: Margins.only(bottom: 12),
            padding: HtmlPaddings.only(left: 20),
          ),
          "li": Style(
            margin: Margins.only(bottom: 4),
          ),
          "hr": Style(
            margin: Margins.symmetric(vertical: 16),
            border: Border(
              top: BorderSide(color: Colors.grey[300]!, width: 1),
            ),
          ),
          "img": Style(
            width: Width.auto(),
            height: Height.auto(),
            margin: Margins.only(top: 8, bottom: 8),
            alignment: Alignment.center,
          ),
          "figure": Style(
            margin: Margins.symmetric(vertical: 16),
            alignment: Alignment.center,
          ),
          "figcaption": Style(
            fontSize: FontSize(14),
            color: Colors.grey[600],
            textAlign: TextAlign.center,
            margin: Margins.only(top: 8),
          ),
          "span": Style(
              // 支持内联样式
              ),
          "div": Style(
              // 支持div容器
              ),
        },
        extensions: [
          TagExtension(
            tagsToExtend: {"img"},
            builder: (extensionContext) {
              final element = extensionContext.element;
              final src = element?.attributes['src'];
              final alt = element?.attributes['alt'] ?? '';
              
              if (src != null && src.isNotEmpty) {
                return Container(
                  margin: const EdgeInsets.symmetric(vertical: 8),
                  child: GestureDetector(
                    onTap: () {
                      // 点击图片进行全屏预览
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          fullscreenDialog: true,
                          builder: (context) => ImagePreview(
                            imagePaths: [src],
                            initialIndex: 0,
                            isNetworkImage: true,
                          ),
                        ),
                      );
                    },
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Image.network(
                        src,
                        fit: BoxFit.contain,
                        width: double.infinity,
                        loadingBuilder: (context, child, loadingProgress) {
                          if (loadingProgress == null) return child;
                          return Container(
                            height: 200,
                            alignment: Alignment.center,
                            child: CircularProgressIndicator(
                              value: loadingProgress.expectedTotalBytes != null
                                  ? loadingProgress.cumulativeBytesLoaded /
                                      loadingProgress.expectedTotalBytes!
                                  : null,
                            ),
                          );
                        },
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            height: 200,
                            decoration: BoxDecoration(
                              color: Colors.grey[200],
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.broken_image,
                                  size: 48,
                                  color: Colors.grey[400],
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  alt.isNotEmpty ? alt : '图片加载失败',
                                  style: TextStyle(
                                    color: Colors.grey[600],
                                    fontSize: 14,
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                );
              }
              return const SizedBox.shrink();
            },
          ),
        ],
        onLinkTap: (url, attributes, element) {
          // 处理链接点击
          if (url != null) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('链接: $url')),
            );
          }
        },
      );
    } else {
      // 如果是纯文本，使用普通Text widget
      return Text(
        processedContent,
        style: const TextStyle(
          fontSize: 16,
          height: 1.6,
          color: Colors.black87,
        ),
      );
    }
  }
  
  String _decodeHtmlEntities(String text) {
    // 处理HTML实体
    String result = text
        .replaceAll('&lt;', '<')
        .replaceAll('&gt;', '>')
        .replaceAll('&amp;', '&')
        .replaceAll('&quot;', '"')
        .replaceAll('&#39;', "'");
    
    // 打印原始内容，用于调试
    
    // 查找所有<img>标签，用于调试
    RegExp imgTagRegex = RegExp(r'<img[^>]*>');
    final imgTags = imgTagRegex.allMatches(result).map((m) => m.group(0)).toList();
    
    // 查找所有src属性，用于调试
    RegExp srcAttrRegex = RegExp(r'src="([^"]*?)"');
    final srcAttrs = srcAttrRegex.allMatches(result).map((m) => m.group(1)).toList();
    
    // 处理图片URL中的反引号 - 方法1：处理src属性中的反引号
    RegExp imgSrcRegex = RegExp(r'src="`([^`]*?)`"');
    result = result.replaceAllMapped(imgSrcRegex, (match) {
      String url = match.group(1) ?? "";
      return 'src="$url"';
    });
    
    // 处理图片URL中的反引号 - 方法2：处理任何包含反引号的URL
    RegExp altImgRegex = RegExp(r'`(https?://[^`]+)`');
    result = result.replaceAllMapped(altImgRegex, (match) {
      String url = match.group(1) ?? "";
      return url;
    });
    
    // 处理图片URL中的反引号 - 方法3：处理整个img标签
    RegExp imgTagWithBackticksRegex = RegExp(r'<img[^>]*src="`([^`]+)`"[^>]*>');
    result = result.replaceAllMapped(imgTagWithBackticksRegex, (match) {
      String fullTag = match.group(0) ?? "";
      String url = match.group(1) ?? "";
      return fullTag.replaceAll('src="`$url`"', 'src="$url"');
    });
    
    return result;
  }

  Widget _buildInteractionStats(FishingTechnique technique) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem(Icons.thumb_up, '${technique.likeCount}', '点赞'),
          _buildStatItem(Icons.favorite, '${technique.favoriteCount}', '收藏'),
          _buildStatItem(Icons.comment, '${technique.commentCount}', '评论'),
        ],
      ),
    );
  }

  Widget _buildTags(FishingTechnique technique) {
    if (technique.tags.isEmpty) return const SizedBox.shrink();
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '相关标签',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: technique.tags.map((tag) {
            return Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 12,
                vertical: 6,
              ),
              decoration: BoxDecoration(
                color: Colors.blue[50],
                borderRadius: BorderRadius.circular(16),
                border: Border.all(color: Colors.blue[200]!),
              ),
              child: Text(
                tag,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.blue[700],
                  fontWeight: FontWeight.w500,
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  Widget _buildAuthorInfo(FishingTechnique technique) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.blue[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.blue[100]!),
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: 24,
            backgroundColor: Colors.blue[200],
            child: Text(
              technique.author.isNotEmpty ? technique.author[0] : '专',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.blue[700],
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  technique.author,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '发布时间：${technique.createTime}',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  }